<?php
require_once 'models/glossary_item_page.inc';
require_once 'models/TCMSPublisher.inc';

class TMSGlossaryItemPageItem extends TCMSPageItem {
	public function __get($nm){
		switch ($nm){
			case 'GlossaryItem':return $this->Model->GetGlossaryItem($this);break;
			default:return parent::__get($nm);break;
		}
	}
}

/**
 * 
 * @author kras
 * @property TMSGlossaryModel $GlossaryModel
 */

class TMSGlossaryItemPublisher extends TCMSPublisher {
	
/**
 * @var TMSGlossaryModel
 */
	protected $_ioc_glossary_model_;
	
	protected function afterConstruct(){
		$this->_conf_classname_ = 'TMSGlossaryItemPage';
	}
	
	public function postProcessProperties(){
		parent::postProcessProperties();
		$this->propertyMetas['GlossaryItemId']->ReadOnly = true;
		$this->propertyMetas['GlossaryItemClass']->ReadOnly = true;
		$this->propertyMetas['GlossaryItem'] = new TOrmReferencePropertyMeta('GlossaryItem', 'Glossary item', '');
		$this->propertyMetas['GlossaryItem']->ReadOnly = true;
	}
	
	public function CheckItemProperty(TNOrmObject $object, TOrmPropertyMeta $property){
		if ($property->Name() == 'GlossaryItem')
			$property->ClassName = $object->GlossaryItemClass;
		return true;
	}
	
/**
 * @param IItem $item
 * @return IItem
 */
	public function createIssue(IItem $item){
		return $this->CreateItem(array('Title'=>(string)$item,'IsPublished'=>false,'GlossaryItemId'=>$item->ItemId(),'GlossaryItemClass'=>$item->ClassName()));
	}
	
	/**
	 * @param IItem $item
	 * @return IItem
	 */
	public function ItemIssue(IItem $item){
		$dummy = new TMSGlossaryItemPage();
		$dummy->GlossaryItemId = $item->Base->Id;
		$dummy->GlossaryItemClass = $item->ClassName();
		$dummy = $this->Adapter->Load($dummy);
		if ($dummy instanceof TMSGlossaryItemPage)
			return $this->WrapObject($dummy);
		return parent::ItemIssue($item);
	}
	
	public function AgregationContainer(IItem $page){
		if ($this->TypesModel)
			if ($t = $this->TypesModel->GetItem($page->GlossaryItemClass)){
				if ($aa = $t->AgregationAttribute){
					if ($ac = $page->GlossaryItem->$aa)
						return $this->ItemIssue($ac);	
				}
			}
		return null;
	}
	
	public function OnItemChange(IItem $item){
		if ($page = $this->ItemIssue($item)){
			$this->autoAgregate($item, $page);
		}		
	}
	
	public function GetGlossaryItem(IItem $page){
		return $this->GlossaryModel->GetGlossaryItem($page->GlossaryItemClass,$page->GlossaryItemId);
	}
	
	public function WrapObject($object,  array &$caller_stack = array()){
		if ($object instanceof TMSGlossaryItemPage)
			return new TMSGlossaryItemPageItem($object, $this);
		return parent::WrapObject($object,$caller_stack);
	}
}